import { useEffect, useRef, useState } from 'react';

export function useResize() {
  const el = useRef();
  const [wh, setSize] = useState({
    width: 0,
    height: 0,
  });

  function onResize() {
    if (!el.current) {
      return;
    }
    function toNumber(num) {
      return Number(num.replace('px', ''));
    }
    const style = getComputedStyle(el.current);
    const newHeight = el.current.clientHeight + toNumber(style.marginTop) + toNumber(style.marginBottom) + toNumber(style.paddingTop) + toNumber(style.paddingBottom);
    const newWidth = el.current.clientWidth + toNumber(style.marginLeft) + toNumber(style.marginRight) + toNumber(style.paddingLeft) + toNumber(style.paddingRight);

    setSize({
      width: newWidth,
      height: newHeight,
    });
  }

  useEffect(() => {
    onResize();
    window.addEventListener('resize', onResize);

    return () => {
      window.removeEventListener('resize', onResize);
    };
  }, []);

  return {
    el,
    width: wh.width,
    height: wh.height,

    onResize,
  };
}
